/*
 * @Author: wuhao930406 1148547900@qq.com
 * @Date: 2023-07-05 15:36:04
 * @LastEditors: wuhao930406 1148547900@qq.com
 * @LastEditTime: 2023-10-08 10:04:48
 * @FilePath: /legion-iot/src/pages/dashboard3d/index.jsx
 * @Description: three @types/three @react-three/fiber
 *
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
 */
import { Collapse, theme, Spin, Button, Modal } from "antd";
import React, { useState, Suspense, useRef, useEffect } from "react";
import styles from "./index.less";
import { useLocation, useOutletContext, useSearchParams, history } from "umi";
import Building from "./components/Building";
import Safe from "./components/Safe";
import { getFetch } from "@/utils/doFetch";
import { useAsyncEffect, useFullscreen, useRequest } from "ahooks";
import {
  FullscreenOutlined,
  FullscreenExitOutlined,
  RollbackOutlined,
} from "@ant-design/icons";
import { Scrollbars } from "react-custom-scrollbars";
import { zuodata, zhongdata, youdata } from "./components/cast/config";
import VideoPlayer from "./components/VideoPlayer";
import datas from "../dashboard/mock";

const idconfig = {
  西欧名邸: 8,
  景盛家园: 7,
  万林名都城: 6,
  如皋科技创业园: 5,
};

const dataconfig = {
  "1单元1": {
    data: zuodata?.first,
  },
  "1单元2": {
    data: zuodata?.second,
  },
  "1单元3": {
    data: zuodata?.third,
  },
  "1单元4": {
    data: zuodata?.fourth,
  },
  "1单元5": {
    data: zuodata?.fifth,
  },
  "2单元1": {
    data: zhongdata?.first,
  },
  "2单元2": {
    data: zhongdata?.second,
  },
  "3单元1": {
    data: youdata?.first,
  },
  "3单元2": {
    data: youdata?.second,
  },
  "3单元3": {
    data: youdata?.third,
  },
  "3单元4": {
    data: youdata?.fourth,
  },
  "3单元5": {
    data: youdata?.fifth,
  },
  "3单元6": {
    data: youdata?.sixth,
  },
};

const colors = ["#ff4800", "#1a9c00", "#0274ff"];

const arrs = {
  万林名都城1栋: [88, 60, 30, 39, 25, 64, 81, 76, 41, 69, 32, 82],
  万林名都城6栋: [60, 30, 39, 25, 64, 81, 76, 41, 69, 32, 82, 60],
  西欧名邸1栋: [39, 25, 64, 81, 76, 41, 69, 32, 82, 60, 30, 39],
  西欧名邸1栋: [64, 81, 76, 41, 69, 32, 82, 60, 30, 39, 25, 64],
};

const sensortype = {
  "32_channel": "32通道开关量采集终端",
  pressure_mpa: "压力表Mpa",
  pressure_pa: "压力表pa",
  liquid_m: "液位表m",
  anemometer: "风速仪",
};

const baseconf = {
  如皋科技创业园: "rgc",
  万林名都城: "wlm",
  景盛家园: "jsj",
  西欧名邸: "xom",
};

function getinfo(list, curconfig) {
  let res = list?.filter?.((item, index) => {
    return item.remark === curconfig?.okey;
  })?.[0];

  return res ?? curconfig;
}

const Layout = ({
  setActiveFloor,
  score,
  title,
  activeFloor,
  searchParams,
  theindex,
  setIndex,
  setIndexs,
  action,
  token,
}) => {
  const { colorTextBase, colorBgSecondary, colorBgThird } = token;

  const style = {
    style: {
      background: colorBgSecondary,
      pointerEvents: "fill",
      padding: 12,
      backdropFilter: "blur(4px)",
    },
  };
  const name = searchParams.get("name");
  const dong = searchParams.get("dong");
  const okeys = searchParams.get("okeys");
  const active = searchParams.get("active");
  const deviceid = searchParams.get("deviceid");

  const { data } = useRequest(async () => {
    let res = await getFetch({
      url: "/device",
      params: {
        village_id: idconfig[name],
        build_number: dong,
        is_all: 1,
      },
    });
    localStorage.setItem("ALIST", JSON.stringify(res?.data?.dataList));
    return res?.data?.dataList;
  });

  useEffect(() => {
    setActiveFloor(active);
  }, [active]);

  useAsyncEffect(async () => {
    if (!data) return;
    const alldata = [
      ...Object.values(zuodata),
      ...Object.values(zhongdata),
      ...Object.values(youdata),
    ].flat();
    const cur = alldata?.filter((it) => it?.okey === okeys)?.[0] ?? {};

    const reses = getinfo(data, {
      okey: okeys,
    });

    setIndex({
      ...reses,
      sensors: cur?.sensors,
      okey: okeys,
    });
    let res = await getFetch({ url: "/device/" + deviceid });

    setinfos(res?.data);
  }, [okeys, data, deviceid]);

  const [infos, setinfos] = useState({});
  console.log(theindex);

  return (
    <div className={styles?.layout} style={{ pointerEvents: "none" }}>
      <div>
        <div
          style={{
            ...style?.style,
            flex: "none",
            height: 260,
          }}
        >
          <h2>综合安全评分</h2>
          <Safe data={datas[baseconf?.[name]]}></Safe>
        </div>
        <div style={{ ...style.style, flex: 2 }} className={styles.hidescroll}>
          <h2>
            <span>楼层概览</span>
            <span
              style={{ float: "right", cursor: "pointer", color: "#f76e03" }}
              onClick={() => {
                setActiveFloor(null);
                setIndexs(null)
              }}
            >
              重置
            </span>
          </h2>
          <Scrollbars
            thumbMinSize={10}
            autoHide
            style={{
              width: "100%",
              height: "100%",
            }}
            hideTracksWhenNotNeeded
          >
            <div style={{ marginTop: 12, display: "block" }}>
              {score < 60
                ? arrs?.[
                    Object.keys(arrs)?.includes(title)
                      ? title
                      : Object.keys(arrs)?.[0]
                  ].map((it, i) => {
                    return (
                      <div
                        key={i}
                        className="item"
                        style={{
                          backgroundColor:
                            activeFloor === i + 1
                              ? "rgba(2, 116, 255,0.2)"
                              : colorBgSecondary,
                        }}
                        onClick={() => {
                          setActiveFloor(i + 1);
                        }}
                      >
                        <b>{i + 1}楼</b>
                        <span
                          style={{
                            color:
                              it < 50
                                ? "#ff4800"
                                : it < 70
                                ? "#1a9c00"
                                : "#0274ff",
                          }}
                        >
                          {it}分
                        </span>
                      </div>
                    );
                  })
                : [
                    {
                      title: "1单元",
                      score: parseInt(
                        [88, 89, 81, 86, 83].reduce(
                          (prev, next) => prev + next
                        ) / 5
                      ),
                      floor_score: [88, 89, 81, 86, 83],
                    },
                    {
                      title: "2单元",
                      score: (69 + 49) / 2,
                      floor_score: [69, 49],
                    },
                    {
                      title: "3单元",
                      score:
                        [96, 91, 90, 84, 68, 78].reduce(
                          (prev, next) => prev + next
                        ) / 6,
                      floor_score: [96, 91, 90, 84, 68, 78],
                    },
                  ]?.map((its, index) => {
                    return (
                      <div key={index}>
                        <div className="spread">
                          <b style={{ display: "block", margin: 4 }}>
                            {its.title}
                          </b>
                          <a href="">{its?.score}</a>
                        </div>

                        {its.floor_score?.map((it, i) => {
                          return (
                            <div
                              key={i}
                              className="item"
                              style={{
                                backgroundColor:
                                  activeFloor === its.title + (i + 1)
                                    ? "rgba(2, 116, 255,0.2)"
                                    : colorBgSecondary,
                              }}
                              onClick={() => {
                                setActiveFloor(its.title + (i + 1));
                              }}
                            >
                              <b>
                                {i == its.floor_score?.length - 1 &&
                                its?.title == "3单元"
                                  ? "顶"
                                  : i + 1}
                                楼
                              </b>
                              <span
                                style={{
                                  color:
                                    it < 50
                                      ? "#ff4800"
                                      : it < 70
                                      ? "#1a9c00"
                                      : "#0274ff",
                                }}
                              >
                                {it}分
                              </span>
                            </div>
                          );
                        })}
                      </div>
                    );
                  })}
            </div>
          </Scrollbars>
        </div>
      </div>
      <div>
        <div
          style={{
            padding: 0,
            pointerEvents: "none",
            display: "flex",
            justifyContent: "center",
            flexDirection: "row",
          }}
        >
          <h1
            style={{
              background: colorBgSecondary,
              pointerEvents: "fill",
              padding: 12,
              backdropFilter: "blur(4px)",
              fontSize: 22,
              height: 48,
              color: colorTextBase,
              borderRadius: 8,
              letterSpacing: 2,
              fontWeight: "bolder",
              display: "flex",
              alignItems: "center",
            }}
          >
            {title}
            {action}
          </h1>
        </div>
        <div style={{ padding: 0, pointerEvents: "none" }}></div>
      </div>
      <div>
        {activeFloor && activeFloor !== "active" && (
          <div {...style}>
            <h2 style={{ display: "flex", justifyContent: "space-between" }}>
              <span>设备列表</span>
              {theindex?.length > 0 && (
                <a
                  onClick={() => {
                    setIndexs([]);
                  }}
                >
                  返回
                </a>
              )}
            </h2>
            <Scrollbars
              thumbMinSize={10}
              autoHide
              style={{
                width: "100%",
                height: "100%",
              }}
              hideTracksWhenNotNeeded
            >
              <div style={{ marginTop: 12 }}>
                {theindex?.length > 0 ? (
                  <div
                    style={{
                      display: "flex",
                      flexDirection: "column",
                      alignItems: "flex-end",
                    }}
                  >
                    <div style={{ width: "100%" }}>
                      <Collapse
                        accordion
                        items={theindex.map((it, i) => {
                          return {
                            key: it?.id + "|" + i,
                            label: it?.name,
                            children:
                              it?.name === "摄像头" ? (
                                <div style={{ height: 260 }}>
                                  <VideoPlayer source={infos?.url} />
                                </div>
                              ) : (
                                <div>
                                  {infos
                                    ?.filter?.((item, i) =>
                                      it?.sensors?.includes?.(item?.type)
                                    )
                                    .map?.((its, index) => {
                                      return (
                                        <div
                                          key={index}
                                          className="item"
                                          style={{
                                            background: colorBgThird,
                                            flexDirection: "column",
                                          }}
                                        >
                                          {/* <p>
                                            传感器SN:{its?.device_sensor_sn}
                                          </p> */}
                                          <div
                                            style={{
                                              display: "flex",
                                              justifyContent: "space-between",
                                            }}
                                          >
                                            <span>{sensortype[its?.type]}</span>
                                            <b
                                              style={{
                                                color:
                                                  its?.is_lower_alarm ||
                                                  its?.is_high_alarm
                                                    ? "#ff4800"
                                                    : "green",
                                              }}
                                            >
                                              {its?.data?.current_value ?? "-"}
                                            </b>
                                          </div>
                                        </div>
                                      );
                                    })}
                                </div>
                              ),
                          };
                        })}
                        onChange={async (k, row) => {
                          if (!k?.[0]) return;
                          let key = k[0].split("|")[0];

                          const curitem = theindex?.filter(
                            (it) => it.id == key
                          )?.[0];

                          if (curitem?.name === "摄像头") {
                            let res = await getFetch({
                              url: "/device/hik_hls_stream",
                              params: {
                                id: key,
                              },
                            });
                            setinfos(res?.data);

                            return;
                          }

                          let res = await getFetch({ url: "/device/" + key });
                          setinfos(res?.data);
                        }}
                      />
                    </div>
                  </div>
                ) : (
                  <div>
                    {dataconfig[activeFloor]?.data?.map((it, i) => {
                      return (
                        <div
                          key={it?.key}
                          className="item"
                          style={{ background: colorBgSecondary }}
                          onClick={() => {
                            if (it?.name == "消防报警主机") {
                              Modal.info({
                                title: "消防报警主机控制台",
                                width: "96vw",
                                style: { top: "12px" },
                                content: (
                                  <div
                                    style={{
                                      height: "80vh",
                                      width: "100%",
                                      borderRadius: 12,
                                      overflow: "hidden",
                                    }}
                                  >
                                    <iframe
                                      style={{ width: "100%", height: "100%" }}
                                      src="http://221.6.68.150:9090/?row=logins"
                                      frameborder="0"
                                    ></iframe>
                                  </div>
                                ),
                                getContainer: () =>
                                  document.getElementById("conse"),
                              });

                              return;
                            }

                            const res = getinfo(data, it);
                            setIndex({
                              ...res,
                              name: it?.name,
                              sensors: it?.sensors,
                              id: res?.id || it?.defaultid,
                              okey: it?.okey,
                            });
                          }}
                        >
                          <div className="centerl">
                            <div
                              style={{
                                width: 4,
                                height: 18,
                                backgroundColor: colors[2],
                                borderRadius: 50,
                                marginRight: 4,
                              }}
                            ></div>
                            <span>{it?.name}</span>
                          </div>
                          <span>{it?.okey}</span>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </Scrollbars>
          </div>
        )}
      </div>
    </div>
  );
};

function Dashboard() {
  const { mode } = useOutletContext();
  const [dom, setdom] = useState(null);
  const ref = useRef(null);
  const [isFullscreen, { toggleFullscreen }] = useFullscreen(ref);
  const [searchParams, setSearchParams] = useSearchParams();

  const { token } = theme.useToken();

  const { colorBgSecondary, colorBorder } = token;

  const [activeFloor, setActiveFloor] = useState(null);

  const [theindex, setIndex] = useState([]);

  useEffect(() => {
    setIndex([]);
  }, [activeFloor]);

  return (
    <Suspense
      fallback={
        <Spin
          style={{
            width: "100%",
            height: "calc(100vh - 24px)",
            maxHeight: "100%",
          }}
          className="center"
          tip="模型加载中..."
          spinning={true}
          size="large"
        ></Spin>
      }
    >
      <div
        id="conse"
        className={styles?.dashcontainer}
        style={{ boxShadow: `0 0 16px ${colorBorder}` }}
        ref={ref}
      >
        <Building
          mode={mode}
          setdom={setdom}
          activeFloor={activeFloor}
          score={searchParams.get("score")}
          setIndex={(index) => {
            setIndex((s) => {
              let news = JSON.parse(JSON.stringify(s));
              const okeylist = news.map((it) => it.okey);
              if (!okeylist.includes(index.okey)) {
                news.push(index);
              } else {
                news = news.filter((it) => it.okey !== index.okey);
              }
              return news;
            });
          }}
          theindex={theindex}
        ></Building>

        <Layout
          colorBorder={colorBorder}
          colorBgSecondary={colorBgSecondary}
          dom={dom}
          title={searchParams.get("name") + searchParams.get("dong") + "栋"}
          score={searchParams.get("score")}
          searchParams={searchParams}
          setActiveFloor={setActiveFloor}
          activeFloor={activeFloor}
          theindex={theindex}
          setIndexs={setIndex}
          setIndex={(index) => {
            setIndex((s) => {
              let news = JSON.parse(JSON.stringify(s));
              if (news.indexOf(index) == -1) {
                news.push(index);
              } else {
                news = news.filter((it) => it !== index);
              }
              return news;
            });
          }}
          action={
            <>
              <Button
                type="text"
                icon={
                  isFullscreen ? (
                    <FullscreenExitOutlined />
                  ) : (
                    <FullscreenOutlined />
                  )
                }
                style={{ marginLeft: 12 }}
                onClick={() => {
                  toggleFullscreen();
                }}
              ></Button>

              <Button
                ghost
                type="text"
                icon={<RollbackOutlined />}
                onClick={() => {
                  history.go(-1);
                }}
              ></Button>
            </>
          }
          token={token}
        ></Layout>
      </div>
    </Suspense>
  );
}

export default Dashboard;
